// pages/myCoupon/myCoupon.js
const couponService = require('../../../../api/couponService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    type: 'DISCOUNT',
    page: 1,
    pageSize: 10,
    externalPage: 0,
    limit: 10,
    available: true,
    searchCount: true,
    pageCount: 1,
    couponsList: [],
    discountCoupon: [], // 优惠券
    freeshipCoupon: [], // 运费券
    x: 0,
    y: 60,
    scale: 2,
    homeBack: false,
    loading: true,
    member: {},
    load: false,
    loadingText: '正在加载...',
    noCouponData: false
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  clickCategory: function () {
    if (this.data.type === 'DISCOUNT') {
      this.setData({
        type: 'FREESHIP',
      })
    } else {
      this.setData({
        type: 'DISCOUNT',
      })
    }
  },
  // 前往券详情页面
  toCouponDetails: function (val) {
    console.log(val.currentTarget.dataset.activityid, val.currentTarget.dataset.type)
    const isExternal = val.currentTarget.dataset.external
    const couponActivityId = val.currentTarget.dataset.activityid
    const type = val.currentTarget.dataset.type
    const couponsList = this.data.couponsList
    const id = val.currentTarget.dataset.id
    if (!isExternal) {
      wx.navigateTo({
        url: '../couponDetails/couponDetails?couponActivityId=' + couponActivityId + '&type=' + type + '&couponId=' + id + '&isExternal=' + isExternal
      })
    } else {
      // 外部券详情跳转
      let tempCoupons = null
      couponsList.forEach(item => {
        if (item.externalCardNum === id) {
          tempCoupons = item
        }
      })

      let coupon = JSON.stringify(tempCoupons)
      console.log(coupon)
      wx.navigateTo({
        url: '../couponDetails/couponDetails?couponActivityId=' + couponActivityId + '&type=' + type + '&couponId=' + id + '&isExternal=' + isExternal + '&coupon=' + coupon
      })
    }
  },
  // 前往历史优惠券
  toCouponHistory: function (val) {
    wx.navigateTo({
      url: '../couponHistory/couponHistory?type=' + val.currentTarget.dataset.type
    })
  },
  // 去购物
  toIndex: function () {
    wx.switchTab({
      url: '../../index/index'
    })
  },
  // 查询券列表
  getCouponList: function (page, pageSize, searchCount, memberId) {
    let tempList = []
    // 优惠券
    let tempDiscountCoupon = []
    // 运费券
    let tempFreeshipCoupon = []
    let memberMobile = this.data.member.mobile
    let postData = {
      page: page,
      pageSize: pageSize,
      searchCount: searchCount,
      memberIdEquals: memberId,
      memberMobileEquals: memberMobile,
      orderDirection: 'desc',
      orderField: 'assign_time',
      statusEquals: 'OPEN'
    }
    let listData = couponService.queryCoupon(postData).then(res => {
      wx.hideToast()
      this.setData({
        pageCount: res.pageCount
      })
      const that = this;
      console.log(res);
      if (res.records && res.records.length > 0) {
        res.records.forEach(item => {
          var tempItem = {
            id: item.id,
            faceValue: item.faceValue,
            balance: item.balance,
            couponTypeName: item.couponTypeName,
            couponActivityName: item.couponActivityName,
            bytimeStart: item.bytimeStart,
            bytimeEnd: item.bytimeEnd,
            status: item.status,
            statusDesc: that.handleCouponStatus(item.status),
            rate: item.rate || item.rate === 0 ? (item.rate * 10).toFixed(1) : '',
            function: item.function,
            name: that.handleCouponName(item.function),
            couponActivityId: item.couponActivityId,
            isExternal: false
          }
          if (item.bytimeStart) {
            // let startTime = item.bytimeStart.split(' ')[0]
            // let endTime = item.bytimeEnd.split(' ')[0]
            let startTime = item.bytimeStart.slice(0, 16)
            let endTime = item.bytimeEnd.slice(0, 16)
            let effectiveTime = startTime + ' ~ ' + endTime
            tempItem = {
              ...tempItem,
              effectiveTime: effectiveTime
            }
          } else {
            tempItem = {
              ...tempItem,
              effectiveTime: ''
            }
          }
          if (item.function === 'FREESHIP') {
            tempFreeshipCoupon.push(tempItem)
          } else {
            tempDiscountCoupon.push(tempItem)
          }
        })
        let tempCouponsList = []
        tempCouponsList = [].concat(that.data.couponsList)
        tempCouponsList = tempCouponsList.concat(res.records)
        that.setData({
          couponsList: tempCouponsList
        })
      }
      tempList.push(tempDiscountCoupon, tempFreeshipCoupon)
      return tempList
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
      tempList.push(tempDiscountCoupon, tempFreeshipCoupon)
      return tempList
    })
    return listData
  },
  handleCouponName: function (name) {
    if (name === 'FREESHIP') {
      return '运费券'
    } else if (name === 'DISCOUNT') {
      return '折扣券'
    } else if (name === 'CASH') {
      return '现金券'
    } else if (name === 'GIFT') {
      return '礼品券'
    } else {
      return '优惠券'
    }
  },
  handleCouponStatus: function (status) {
    if (status === 'OPEN') {
      return '已发放'
    } else if (status === 'USED') {
      return '已使用'
    } else if (status === 'EXPIRE') {
      return '已过期'
    } else if (status === 'CANCEL') {
      return '已作废'
    } else if (status === 'MADE') {
      return '已生成'
    } else {
      return '已领取'
    }
  },
  // 查询外部券
  queryExternalCoupons: function () {
    const that = this
    let tempList = []
    // 优惠券
    let tempDiscountCoupon = []
    // 运费券
    let tempFreeshipCoupon = []
    let tempPage = that.data.externalPage
    let memberId = that.data.member.id
    let pageSize = that.data.pageSize
    let postData = {
      memberId: memberId,
      page: tempPage,
      pageSize: pageSize
    }
    let listData = couponService.queryExternalCoupons(postData).then(res => {
      wx.hideToast()
      console.log(res)
      if (res && res.length > 0) {
        let tempExternalList = []
        res.forEach(item => {
          if (item.status === 'OPEN') {
            tempExternalList.push(item)
            var tempItem = {
              id: item.externalCardNum,
              faceValue: item.faceValue,
              balance: item.balance,
              couponTypeName: item.couponTypeName,
              couponActivityName: item.couponActivityName,
              bytimeStart: item.bytimeStart,
              bytimeEnd: item.bytimeEnd,
              status: item.status,
              statusDesc: that.handleCouponStatus(item.status),
              rate: item.rate || item.rate === 0 ? (item.rate * 10).toFixed(1) : '',
              function: item.function,
              name: that.handleCouponName(item.function),
              couponActivityId: item.couponActivityId,
              isExternal: true
            }
            if (item.bytimeStart) {
              let startTime = item.bytimeStart.split(' ')[0]
              let endTime = item.bytimeEnd.split(' ')[0]
              let effectiveTime = startTime + ' 至 ' + endTime
              tempItem = {
                ...tempItem,
                effectiveTime: effectiveTime
              }
            } else {
              tempItem = {
                ...tempItem,
                effectiveTime: ''
              }
            }
            if (item.function === 'FREESHIP') {
              tempFreeshipCoupon.push(tempItem)
            } else {
              tempDiscountCoupon.push(tempItem)
            }
          }
        })
        console.log(that.data.couponsList)
        let tempCouponsList = []
        tempCouponsList = [].concat(that.data.couponsList)
        tempCouponsList = tempCouponsList.concat(tempExternalList)
        that.setData({
          couponsList: tempCouponsList
        })
      }
      tempList.push(tempDiscountCoupon, tempFreeshipCoupon)
      return tempList
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
      tempList.push(tempDiscountCoupon, tempFreeshipCoupon)
      return tempList
    })
    Promise.all([listData]).then(res => {
      console.log(res)
      if (res[0] && (res[0][0].length > 0 || res[0][1].length > 0)) {
        console.log(res[0])
        that.setCoupons(res[0])
        tempPage++
        that.setData({
          externalPage: tempPage
        })
      } else {
        that.setData({
          load: false,
          noCouponData: true
        })
      }
    })
  },
  toHome: function () {
    wx.switchTab({
      url: '../../index/index'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    const self = this;
    var pageStack = getCurrentPages()
    console.log(pageStack)
    if (pageStack.length === 1) {
      this.setData({
        homeBack: true
      })
    }
    try {
      var memberInfo = wx.getStorageSync('wj_member')
      if (memberInfo) {
        const login = self.checkAuth()
        self.setData({
          member: memberInfo
        })
        if (login) {
          if (app.globalData.userInfo.member) {
            let listData = self.getCouponList(self.data.page, self.data.pageSize, self.data.searchCount, memberInfo.id)
            Promise.all([listData]).then(res => {
              console.log(res)
              if (res[0] && res[0][0].length > 0) {
                self.setData({
                  discountCoupon: res[0][0], // 优惠券
                  freeshipCoupon: res[0][1], // 运费券
                })
                if (res[0][0] && res[0][0].length < self.data.limit) {
                  self.queryExternalCoupons()
                }
              } else {
                self.queryExternalCoupons()
              }
              self.setData({
                loading: false
              })
              // wx.hideToast()
            })
          } else {
            wx.showToast({
              title: '您还不是会员，请先绑定手机号码成为会员',
              icon: 'none',
              duration: 2000
            })
            self.setData({
              loading: false
            })
          }
        } else {
          wx.showToast({
            title: '您还未授权，请点击头像授权',
            icon: 'none',
            duration: 2000
          })
          self.setData({
            loading: false
          })
        }
      } else {
        wx.showToast({
          title: '您还不是会员，请先绑定手机号码成为会员',
          icon: 'none',
          duration: 2000
        })
        self.setData({
          loading: false
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("onPullDownRefresh")
    const that = this
    that.setData({
      page: 1,
      externalPage: 0,
      couponsList: []
    })
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let tempList = this.getCouponList(1, that.data.pageSize, that.data.searchCount, that.data.member.id)
      Promise.all([tempList]).then(res => {
        console.log(res[0])
        if (res[0] && res[0][0].length > 0) {
          that.setData({
            discountCoupon: res[0][0], // 优惠券
            freeshipCoupon: res[0][1], // 运费券
          })
          if (res[0][0] && res[0][0].length < that.data.limit) {
            that.queryExternalCoupons()
          }
        } else {
          that.queryExternalCoupons()
        }
        wx.stopPullDownRefresh()
      })
    } else {
      wx.showToast({
        title: '您还不是会员，请绑定手机号成为会员~',
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("onReachBottom")
    this.loadingCoupon()
  },
  loadingCoupon: function () {
    const that = this
    that.setData({
      load: true
    })
    let index = that.data.page
    const memberId = that.data.member.id
    index++
    let tempList = this.getCouponList(index, that.data.pageSize, that.data.searchCount, that.data.member.id)
    Promise.all([tempList]).then(res => {
      if (res[0] && (res[0][0].length > 0 || res[0][1].length > 0)) {
        console.log(res[0])
        that.setCoupons(res[0])
        that.setData({
          page: index
        })
        if (res[0].length < that.data.limit) {
          // 查询到的内部券数量不够一屏，查询外部券
          console.log('内部券数量不够，查询外部券')
          that.queryExternalCoupons()
        }
      } else {
        // 内部券加载完开始查询外部券
        that.queryExternalCoupons()
      }
      wx.stopPullDownRefresh()
    })
  },
  // 渲染查询到的券数据
  setCoupons: function (coupons) {
    const that = this
    let tempDiscountCoupon = that.data.discountCoupon
    let tempFreeshipCoupon = that.data.freeshipCoupon
    tempDiscountCoupon = tempDiscountCoupon.concat(coupons[0])
    tempFreeshipCoupon = tempFreeshipCoupon.concat(coupons[1])
    that.setData({
      discountCoupon: tempDiscountCoupon, // 优惠券
      freeshipCoupon: tempFreeshipCoupon, // 运费券
      load: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})